#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cerrno>
using namespace std;

int main(int argc, char* argv[])
{
    if (argc <= 2)
    {
        cerr << "Usage: " << argv[0] << " <server> <port>" << endl;
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi(argv[2]);

    // 确定服务器地址
    struct sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_port = htons(port);
    inet_pton(AF_INET, ip, &address.sin_addr);
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    assert (sockfd >= 0);
    // 绑定套接字
    int ret = bind(sockfd, (struct sockaddr*)&address, sizeof(address));
    assert (ret != -1);
    // 监听套接字
    int ret = listen(sockfd, 5);
    assert (ret != -1);
    // 接受客户端连接
    struct sockaddr_in client_address;
    socklen_t client_address_length = sizeof(client_address);
    int connfd = accept(sockfd, (struct sockaddr*)&client_address, &client_address_length);
    if (connfd < 0)
    {
        cerr << "Accept failed: " << strerror(errno) << endl;
    }
    else
    {
        // 接收紧急数据
        char buffer[1024];
        memset(buffer, 0, sizeof(buffer));
        int ret = recv(connfd, buffer, sizeof(buffer) - 1, MSG_OOB);
        if (ret > 0)
        {
            buffer[ret] = '\0'; // 确保字符串结束
            cout << "Received urgent data: " << buffer << endl;
        }
        else if (ret < 0)
        {
            cerr << "Receive urgent data failed: " << strerror(errno) << endl;
        }

        // 接收正常数据
        ret = recv(connfd, buffer, sizeof(buffer), 0);
        if (ret > 0)
        {
            buffer[ret] = '\0'; // 确保字符串结束
            cout << "Received normal data: " << buffer << endl;
        }
        else if (ret < 0)
        {
            cerr << "Receive normal data failed: " << strerror(errno) << endl;
        }

        // 关闭连接
        close(connfd);
    }

    close(sockfd); // 关闭监听套接字
    
    return 0;
}
